{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Start recording.\n",
      "..............................\n",
      "End recording.\n",
      "{'corpus_no': '7369416037291264722', 'err_msg': 'success.', 'err_no': 0, 'result': ['拆迁。'], 'sn': '20669806681715825878'}\n",
      "val: True\n",
      "拆迁。\n",
      "Start recording.\n",
      "..............................\n",
      "End recording.\n",
      "{'corpus_no': '7369416054261745817', 'err_msg': 'success.', 'err_no': 0, 'result': ['开启。'], 'sn': '90811044551715825883'}\n",
      "val: True\n",
      "开启。\n",
      "Start recording.\n",
      "..............................\n",
      "End recording.\n",
      "{'corpus_no': '7369416071572494366', 'err_msg': 'success.', 'err_no': 0, 'result': ['吨。'], 'sn': '811438359691715825887'}\n",
      "val: True\n",
      "吨。\n",
      "Start recording.\n",
      "..............................\n",
      "End recording.\n",
      "{'corpus_no': '7369416092989463748', 'err_msg': 'success.', 'err_no': 0, 'result': ['关闭。'], 'sn': '745222468671715825892'}\n",
      "val: True\n",
      "关闭。\n",
      "Start recording.\n",
      "..............................\n",
      "End recording.\n",
      "{'corpus_no': '7369416110357150408', 'err_msg': 'success.', 'err_no': 0, 'result': ['退出。'], 'sn': '853748241231715825896'}\n",
      "val: True\n",
      "退出。\n"
     ]
    }
   ],
   "source": [
    "import serial \n",
    "import modbus_tk \n",
    "import wave\n",
    "from pyaudio import PyAudio,paInt16 \n",
    "from aip import AipSpeech \n",
    "import chardet \n",
    "from modbus_tk import modbus_rtu \n",
    "import modbus_tk.defines as cst \n",
    "\n",
    "def ConnectRelay(PORT,ACTION): \n",
    "    \"\"\" \n",
    "    此函数为连接串口继电器模块，为初始函数，必须先调用 \n",
    "    :param PORT: USB-串口端口，需要手动填写，须在计算机中手动查看对应端口 \n",
    "    :return: >0 连接成功，<0 连接超时 \n",
    "     \"\"\" \n",
    "    try: \n",
    "        # c2s03设备默认波特率9600、偶校验、停止位1 \n",
    "        master = modbus_rtu.RtuMaster(serial.Serial(port=PORT,  # type: ignore\n",
    "                                                    baudrate=9600, bytesize=8, \n",
    "                                                    parity='E', stopbits=1)) \n",
    "        master.set_timeout(5.0) \n",
    "        master.set_verbose(True) \n",
    " \n",
    "        # 读输入寄存器 \n",
    "        # c2s03设备默认slave=2, 起始地址=0, 输入寄存器个数2 \n",
    "        master.execute(2, cst.READ_INPUT_REGISTERS, 0, 2) \n",
    " \n",
    "        # 读保持寄存器 \n",
    "        # c2s03设备默认slave=2, 起始地址=0, 保持寄存器个数1 \n",
    "        master.execute(2, cst.READ_HOLDING_REGISTERS, 0, 1)  # 这里可以修改需要读取的功能码 \n",
    " \n",
    "        # 没有报错，返回1 \n",
    "        response_code = 1 \n",
    " \n",
    "    except Exception as exc: \n",
    "        print(str(exc)) \n",
    "        # 报错，返回<0并输出错误 \n",
    "        response_code = -1 \n",
    "        master = None \n",
    "    Switch(master, ACTION)\n",
    "    return response_code, master \n",
    "\n",
    "def Switch(master, ACTION): \n",
    "    \"\"\" \n",
    "    此函数为控制继电器开合函数，如果ACTION=ON则闭合，如果如果ACTION=OFF则断开。 \n",
    "    :param master: 485主机对象，由ConnectRelay产生 \n",
    "    :param ACTION: ON继电器闭合，开启风扇；OFF继电器断开，关闭风扇。 \n",
    "    :return: >0 操作成功，<0 操作失败 \n",
    "    \"\"\" \n",
    "    try: \n",
    " \n",
    "        if \"on\" in ACTION.lower(): \n",
    "            # 写单个线圈，状态常量为0xFF00，请求线圈接通 \n",
    "            # c2s03设备默认slave=2, 线圈地址=0, 请求线圈接通即output_value不等于0 \n",
    "            master.execute(2, cst.WRITE_SINGLE_COIL, 0, output_value=1) \n",
    "        else: \n",
    "            # 写单个线圈，状态常量为0x0000，请求线圈断开 \n",
    "            # c2s03设备默认slave=2, 线圈地址=0, 请求线圈断开即output_value等于0 \n",
    "            master.execute(2, cst.WRITE_SINGLE_COIL, 0, output_value=0) \n",
    "        # 没有报错，返回1 \n",
    "        response_code = 1 \n",
    "    except Exception as exc: \n",
    "        print(str(exc)) \n",
    "        # 报错，返回<0并输出错误 \n",
    "        response_code = -1 \n",
    "    return response_code \n",
    "\n",
    "# 设置采样参数\n",
    "NUM_SAMPLES = 2000\n",
    "# 默认录音3s\n",
    "TIME = 3\n",
    "\n",
    "# 百度智能云平台语音技能密钥\n",
    "BaiduAPP_ID = '61378464'  \n",
    "BaiduAPI_KEY = 'Nl4qAvvDzoGYmy7BxrEHNRzC'\n",
    "SECRET_KEY = 'mf7IPAKWAiVo3Lztxawm052ESO8MrKjS'\n",
    "client = AipSpeech(BaiduAPP_ID, BaiduAPI_KEY, SECRET_KEY)\n",
    "\n",
    "# 保存录音文件\n",
    "def save_wave_file(filename,data):  \n",
    "    wf = wave.open(filename,'wb')  # 打开WAV文档\n",
    "    wf.setnchannels(1)  #配置声道数            \n",
    "    wf.setsampwidth(2)  #配置量化位数              \n",
    "    wf.setframerate(16000) #采样频率         \n",
    "    wf.writeframes(b\"\".join(data))  # 将wav_data转换为二进制数据写入文件\n",
    "    wf.close()\n",
    "\n",
    "# 定义录音函数\n",
    "def record():\n",
    "    print('Start recording.')\n",
    "    # 实例化PyAudio对象，开启声音输入\n",
    "    pa = PyAudio()  \n",
    "    # 打开输入流并设置音频采样参数 1 channel 16K framerate \n",
    "    stream = pa.open(format = paInt16,\n",
    "                        channels = 1,\n",
    "                        rate = 16000,\n",
    "                        input = True,\n",
    "                        frames_per_buffer = NUM_SAMPLES)\n",
    "    # 录音缓存数组\n",
    "    audioBuffer = []   \n",
    "    # 循环采集音频 默认录制3s\n",
    "    count = 0\n",
    "    while count<TIME*10:\n",
    "        # 一次性录音采样字节的大小\n",
    "        string_audio_data = stream.read(NUM_SAMPLES)  \n",
    "        audioBuffer.append(string_audio_data)\n",
    "        count +=1\n",
    "        # 加逗号不换行输出\n",
    "        print('.', end='')  \n",
    "    print('')\n",
    "    print('End recording.')\n",
    "    # 保存录制的语音文件到audio.wav中并关闭输入流\n",
    "    save_wave_file('./audio.wav',audioBuffer)\n",
    "    stream.close()\n",
    "\n",
    "# 语音识别函数\n",
    "def asr_updata():\n",
    "    with open('./audio.wav', 'rb') as f:\n",
    "        audio_data = f.read()\n",
    "    result = client.asr(audio_data, \n",
    "                        'wav', 16000, { \n",
    "                        'dev_pid': 1537,})\n",
    "    print(result)  #打印出来，报错的时候可以查看代码\n",
    "    val = 'result' in result.keys()\n",
    "    print(\"val:\",val)\n",
    "    if val == True:   \n",
    "        result_text = result[\"result\"][0]\n",
    "    else:\n",
    "        result_text = '语音未识别'\n",
    "    return result_text\n",
    "\n",
    "def method1():\n",
    "    while(True):    \n",
    "        record()  #调用录音函数\n",
    "        result_text = asr_updata()\n",
    "        print(result_text)\n",
    "        if result_text==\"开启。\":\n",
    "            ACTION=\"ON\" \n",
    "            ConnectRelay(\"COM4\",ACTION)\n",
    "        if result_text==\"关闭。\":\n",
    "            ACTION=\"OFF\"\n",
    "            ConnectRelay(\"COM4\",ACTION)\n",
    "        if result_text==\"退出。\":\n",
    "            break\n",
    "\n",
    "def method2():\n",
    "    result_text=asr_updata\n",
    "    print(result_text)\n",
    "    if result_text==\"开启。\":\n",
    "        ACTION=\"ON\" \n",
    "        ConnectRelay(\"COM4\",ACTION)\n",
    "    if result_text==\"关闭。\":\n",
    "        ACTION=\"OFF\"\n",
    "        ConnectRelay(\"COM4\",ACTION)\n",
    "\n",
    "if __name__ == '__main__':\n",
    "\n",
    "    method1()\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.11.5"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
